const Blog = require("../models/Blog")
const Class = require("../models/Class")
const sequelize = require("../models/boke");
const { Op } = require("sequelize");

Blog.belongsToMany(Class, {
  through: 'Link'
});
Class.belongsToMany(Blog, {
  through: 'Link'
});

exports.getBlog = async function () {
  const result = await Blog.findAll({
    include: [Class],
  })
  if (result) {
    return result;
  }
}

exports.addBlog = async function (blogObj) {
  const ins = await Blog.create(blogObj)
  blogObj.arr = JSON.parse(blogObj.arr);
  for (let index = 0; index < blogObj.arr.length; index++) {
    const cls = await Class.findAll({
      where: {
        id: blogObj.arr[index]
      }
    })
    await ins.addClass(cls);
  }
  return "1"
}

exports.bokeDetails = async function (obj) {
  await Blog.increment({visitsNum: 1}, { where: {  id: obj.id } }) 
  const result = await Blog.findOne({
    where: {
      id: obj.id
    },
    include: [Class],
  })
  if (result) {
    return result;
  }
}

exports.search = async function (txt) {
  const result = await Blog.findAll({
    where: {
      label: {
          [Op.like]: `%${txt.txt}%`
      },
    },
    include: [Class],
  })
  return result;
}